﻿package com.danielsheldon.GamePack
{	
	import flash.events.EventDispatcher;
	import flash.events.Event;
	import com.danielsheldon.GamePack.events.ResourceEvent;
	/**
	* ...
	* @author Daniel Sheldon
	* 
	*/
	public class ResourceManager extends EventDispatcher
	{
		protected static var dispatcher:EventDispatcher;
		
		private static var resources:Array = [];
		private static var _instance:ResourceManager;
		
		public function ResourceManager(enforcer:SingletonEnforcer = null) 
		{
			if (enforcer == null)
			{
				throw Error("ResourceManager is a singleton. Please use getResource()");
			}
		}
		
		static public function get instance():ResourceManager
		{
			if (_instance == null)
			{
				_instance = new ResourceManager(new SingletonEnforcer());
			}
			
			return _instance;
		}
		
		static public function getResource(kind:String):Resource
		{
			var resource:Resource;
			
			for (var i:int = 0; i < resources.length; i++)
			{
				resource = resources[i];
				if (resource.kind == kind)
				{
					break;
				}
				resource = null;
			}
			
			if (resource == null)
			{
				resource = new Resource(kind)
				resources.push(resource);
				var event:ResourceEvent = new ResourceEvent(ResourceEvent.NEW_RESOURCE, resource);
				dispatchEvent(event);
			}
			
			return resource;
		}
		
		public static function addEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean = false, p_priority:int = 0, p_useWeakReference:Boolean = false):void
		{
			
			if (dispatcher == null) { dispatcher = new EventDispatcher(); }
			
			dispatcher.addEventListener(p_type, p_listener, p_useCapture, p_priority, p_useWeakReference);
      	}
		
		public static function removeEventListener(p_type:String, p_listener:Function, p_useCapture:Boolean = false):void 
		{
			if (dispatcher == null) { return; }
			
			dispatcher.removeEventListener(p_type, p_listener, p_useCapture);
		}
		
		public static function dispatchEvent(p_event:Event):void
		{
			if (dispatcher == null) { return; }
			
			dispatcher.dispatchEvent(p_event);
		}
		
	}
}

class SingletonEnforcer { };